package brands

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/service/app"
	"github.com/go-redis/redis/v8"
	"strconv"
)

var AllBrandsCacheKey = "brands_all"

// 注意　这个只返回所有的 map { brandId: brandName }
func GetAllBrandOptionFromCache(dc model.DbContext) (map[string]interface{}, error) {
	data, errGet := dc.GetRedisConn().Get(AllBrandsCacheKey)
	if errGet != nil {
		if errGet == redis.Nil {
			data, errDb := GetAllBrands()
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			// 如果存在
			if len(data) > 0 {
				dataOption := make(map[string]interface{})
				for id, item := range data {
					idStr := strconv.FormatInt(id, 10)
					dataOption[idStr] = item.BrandName
				}

				jsonData, _ := json.Marshal(dataOption)

				errSet := dc.GetRedisConn().Set(AllBrandsCacheKey, string(jsonData), 0)
				if errSet != nil {
					panic(errSet)
				}

				return dataOption, nil
			} else {
				return make(map[string]interface{}), nil
			}
		}
		panic("Redis-" + errGet.Error())
	}

	var returnData map[string]interface{}
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}
